<?php

namespace App\Http\Controllers\Manager;

use App\Http\Controllers\Controller;
use App\Models\ModConf;
use App\Models\Server;
use App\Models\Video;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Exception;
use Illuminate\Support\Facades\Storage;

class ModConfController extends Controller
{
    public $prefix='manager.modConf';

    public function index($server_id){
        $server=$this->CheckServer($server_id);
        return view($this->prefix.'.index',compact('server'));
    }
    public function list($server_id){
        $server=$this->CheckServer($server_id);
        $list=ModConf::where('server_id',$server_id)->select(['id','path'])->get();
        return $list;
    }

    public function addAuto(Request $request,$server_id){
        $server=$this->CheckServer($server_id);
        $path=$server->path.$server->configPath;
        $path=str_replace('\\','/',$path);
//        return dirname($path);
        $res=$server->GetFileManege()->GetDirList(dirname($path),'.conf.dist');

        if (isset($res['LIST'])){
            $serverlist=ModConf::where('server_id',$server_id)->select('path')->get();
            $serverlistArr=[];
            foreach ($serverlist as $item){
                $serverlistArr[]=$item->path.".conf.dist";
            }
//            return $serverlistArr;
           $count=0;
            foreach ($res['LIST'] as $item){
                if (!in_array($item['filename'],$serverlistArr)){
                    $count++;
                    $this->addModConf($server, str_replace('.conf.dist','',$item['filename']));
                }
            }
            return ['err'=>0,'data'=>1,'mag'=>$count,'more'=>[$res,$path,dirname($path)]];
        }else{
            return $res;
        }


    }

    public function add(Request $request,$server_id){
        $server=$this->CheckServer($server_id);
        $path=$request->get('path');
        $path=str_replace('\\','/',$path);
        $path=dirname($path)."/".basename(basename($path,'.dist'),'.conf');

        $count=ModConf::where('path',$path)->where('server_id',$server_id)->count();
        if ($count>0)
            return ['err'=>-1,'msg'=>'已经添加过了'];

        $res= $server->GetFileManege()->GetFileBody($path.'.conf.dist');

        if ($res['status']){
//            $confListStr=ModConf::ClearConfigStr($server->type,$res);
//            Storage::put("server/{$this->id}{$path}",$confListStr);
//            $path_local=storage_path("app/server/{$this->id}{$path}");
            $this->addModConf($server,$path);
//            $item=new ModConf();
//            $item->server_id=$server_id;
//            $item->path=$path;
//            $item->content=ModConf::ClearConfigStr($server->type,$res['data']);
//            $item->save();
            return ['err'=>0,'data'=>$res];
        }else{
            return ['err'=>-1,'msg'=>$res['msg']];
        }
    }

    private function addModConf($server,$path,$data=''){
        $item=new ModConf();
        $item->server_id=$server->id;
        $item->path=$path;
        if ($data!=='')
            $item->content=ModConf::ClearConfigStr($server->type,$data);
        $item->save();
    }
    public function conf(Request $request,$server_id){
        $server=$this->CheckServer($server_id);
        $id=$request->get('id');
        $item=ModConf::find($id);

        if ($item->server_id!=$server_id){
            return '未授权';
        }

        $res= $server->GetFileManege()->GetFileBody($item->path.'.conf.dist');
        $eol="\n";
//        if(strpos($res['data'],"\r\n") !== false){
//            $eol="\r\n";
//        }

        $arrlist=explode($eol,$item->content);



        if ($res['status']){

            $arrDist=ModConf::ClearConfigStr($server->type,$res['data'],true);
            $arrRes = array_merge(ModConf::ArrToKey($arrDist),ModConf::ArrToKey($arrlist));

            $confCN=[];
            foreach (config('conf-mod') as $modName){
                $confCN+=config($modName);
            }
            foreach ($arrRes as $k=>$v){
                // 添加额外信息
                if (key_exists($k,$confCN)){
                    $arrRes[$k]['info']=$confCN[$k];
                    $arrRes[$k]['info']['loca']=1;
                }else{
                    $arrRes[$k]['info']=[
                        'label'=>$k,
                        'description'=>'',
                        'type'=>'string',
                        'loca'=>0,
                    ];
                }
            }
            return ['err'=>0,'data'=>$arrRes];
        }
    }
    public function confSave(Request $request,$server_id,$modConf_id){
        $server=$this->CheckServer($server_id);
        $item=ModConf::find($modConf_id);
        if ($item->server_id!=$server_id){
            return '未授权';
        }
        $data=$request->get('data');
        $data=explode("\n",$data);
        $data=ModConf::ArrToKey($data);
        $dataStr="";
        foreach ($data as $k=>$v){
            $dataStr.=$k."=".$v["value"]."\n";
        }
        $item->content=$dataStr;
        $item->save();
        $res=$server->GetFileManege()->SaveFileBody($item->path.'.conf',"[worldserver]\n".$dataStr,$server);
        return ['err'=>0,'data'=>$res];
    }
    public function del(Request $request,$server_id,$modConf_id){
        $server=$this->CheckServer($server_id);
        $item=ModConf::find($modConf_id);
        if ($item->server_id!=$server_id){
            return '未授权';
        }
        $item->delete();
        return ['err'=>0];
    }
}
